#pragma strict
//////////////////////////////////////////////////////
///模型放置
//////////////////////////////////////////////////////
class ModelPlace extends EditorWindow{
	static var strModelPrefab:String = "Model Prefab";
	static var strRightwardCount:String = "Rightward Count";
	static var strUpwardCount:String = "Upward Count";
	static var strMaxDistRange:String = "Max Dist Range";
	static var strRandomRotation:String = "Is Random Rotation?";
	static var strPlaceNow:String = "Place Now";
	static var strNeedPrefab:String = "Need prefab in Scene or Project.";
	//准备克隆的模型
	var prefab:Transform;
	//准备放置的个数(水平,竖直)
	var rightCount:int;
	var upCount:int;
	//(水平,竖直)方向最大的距离.
	var distVec:Vector2;
	//是否随机旋转y轴.
	var isRandomRotationY:boolean;

	@MenuItem("Level4/Fbx/ModelPlace")
	static function init(){
		var win:ModelPlace = EditorWindow.GetWindow(ModelPlace) as ModelPlace;
	}
	
	function OnGUI(){
		//prefab label
		GUILayout.Label(strModelPrefab,EditorStyles.boldLabel);
		//prefab object field
		prefab = EditorGUILayout.ObjectField(prefab,Transform,true) as Transform;
		//right text field
		GUILayout.Label(strRightwardCount);
		rightCount = parseInt( GUILayout.TextField(rightCount.ToString()) );
		GUILayout.Label(strUpwardCount);
		upCount = parseInt( GUILayout.TextField(upCount.ToString()) );
		//max range
		distVec = EditorGUILayout.Vector2Field(strMaxDistRange,distVec);
		//random rotation
		isRandomRotationY = EditorGUILayout.Toggle(strRandomRotation,isRandomRotationY);
		//place button
		if( GUILayout.Button(strPlaceNow) ){
			if(prefab){
				PlaceNow();
			}else{
				ShowNotification(GUIContent(strNeedPrefab));
			}
		}
	}
	/**开始放置*/
	function PlaceNow(){
		var pos:Vector3 = prefab.position;
		var startX:float = pos.x;
		var startZ:float = pos.z;
		
		var endX:float = startX + distVec.x;
		var endZ:float = startZ + distVec.y;
		
		var intervalX:float = (endX-startX)/rightCount;
		var intervalZ:float = (endZ-startZ)/upCount;
		
		var curPos:Vector3 = pos;
		var count:int;
		
		for(var i:int = 0;i < rightCount; i++){
			for(var j:int = 0;j < upCount; j++){
				if(i != 0 || j != 0){
					curPos.x = pos.x + (i) * intervalX;
					curPos.z = pos.z + (j) * intervalZ;
					var rotation:Quaternion = prefab.rotation;
					if(isRandomRotationY){
						rotation = Quaternion.Euler(0,Random.Range(0,360),0);
					}
					var clone:Transform = GameObject.Instantiate(prefab,curPos,rotation);
						clone.parent = prefab.parent;
				}
			}
		}
	}
}